<?php

namespace app\api\controller;

use app\common\controller\ApiController;
use app\common\Result;
use joncc\attribute\attr\AuthNeedless;
use joncc\attribute\attr\Comment;
use joncc\attribute\attr\PermissionNeedless;
use think\facade\View;
use think\response\Json;

#[Comment('API文档')]
#[AuthNeedless('index,init')]
#[PermissionNeedless('index,init')]
class Docs extends ApiController
{

    protected function initialize(): void
    {
        $this->model = new \app\common\model\Docs();
        parent::initialize();
    }

    public function index(): string
    {
        return View::fetch();
    }

    public function init(): Json
    {
        $menu = [];
        $form = [];

        $files = scandir(__DIR__);
        foreach ($files as $file) {
            if (in_array($file, ['.', '..'])) {
                continue;
            }

            $class = 'app\api\controller\\' . pathinfo($file, PATHINFO_FILENAME);
            $doc = $this->model->doc($class);
            if (empty($doc)) {
                continue;
            }

            foreach ($doc['method'] as &$method) {
                if (empty($method['params'])) {
                    unset($method['params']);
                    continue;
                }

                $k = implode('/', [$doc['name'], $method['name']]);
                $form[$k] = $method['params'];
                unset($method['params']);
            }

            $menu[] = $doc;
        }

        return Result::success(['menu' => $menu, 'form' => $form]);
    }


    public function test(): string
    {
        return View::fetch();
    }
}